package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.dto.InventoryCheckQueryDTO;
import com.intelligent.mapper.InventoryCheckMapper;
import com.intelligent.pojo.InventoryCheck;
import com.intelligent.service.InventoryCheckService;
import com.intelligent.service.TUserService;
import com.intelligent.vo.InventoryCheckVO;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import com.intelligent.dto.InventoryCheckAddDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* @author 86188
* @description 针对表【inventory_check(库存盘点信息表)】的数据库操作Service实现
* @createDate 2025-08-29 17:02:59
*/
@Service
public class InventoryCheckServiceImpl extends ServiceImpl<InventoryCheckMapper, InventoryCheck>
    implements InventoryCheckService {

    @Autowired
    private TUserService userService;


    @Override
    public IPage<InventoryCheckVO> pageList(InventoryCheckQueryDTO query) {
        // 1. 构建分页参数
        Page<InventoryCheck> page = new Page<>(query.getCurrent(), query.getSize());

        // 2. 构建查询条件
        LambdaQueryWrapper<InventoryCheck> wrapper = new LambdaQueryWrapper<>();

        // 盘点编号模糊查询
        if (StringUtils.isNotBlank(query.getCheckNo())) {
            wrapper.like(InventoryCheck::getCheckNo, query.getCheckNo().trim());
        }

        // 盘点结果精确查询
        if (query.getCheckResult() != null) {
            wrapper.eq(InventoryCheck::getCheckResult, query.getCheckResult());
        }

        // 按盘点时间倒序排序
        wrapper.orderByDesc(InventoryCheck::getCheckTime);

        // 3. 执行分页查询
        IPage<InventoryCheck> checkPage = this.page(page, wrapper);

        // 4. 转换为VO对象
        InventoryCheckVO vo = new InventoryCheckVO();
        vo.setRecords(convertToVOList(checkPage.getRecords()));
        vo.setTotal(checkPage.getTotal());
        vo.setSize(checkPage.getSize());
        vo.setCurrent(checkPage.getCurrent());

        // 创建新的Page对象返回
        Page<InventoryCheckVO> resultPage = new Page<>(checkPage.getCurrent(), checkPage.getSize(), checkPage.getTotal());
        resultPage.setRecords(Collections.singletonList(vo));
        return resultPage;
    }

    /**
     * 将InventoryCheck实体列表转换为InventoryCheckItemVO列表
     */
    private List<InventoryCheckVO.InventoryCheckItemVO> convertToVOList(List<InventoryCheck> checks) {
        if (checks == null || checks.isEmpty()) {
            return Collections.emptyList();
        }

        return checks.stream()
                .map(this::convertToItemVO)
                .collect(Collectors.toList());
    }

    /**
     * 将单个InventoryCheck实体转换为InventoryCheckItemVO
     */
    private InventoryCheckVO.InventoryCheckItemVO convertToItemVO(InventoryCheck check) {
        if (check == null) {
            return null;
        }

        InventoryCheckVO.InventoryCheckItemVO vo = new InventoryCheckVO.InventoryCheckItemVO();
        // 复制基本属性
        BeanUtils.copyProperties(check, vo);

        // 设置盘点结果描述
        vo.setCheckResultDesc(getCheckResultDesc(check.getCheckResult()));

        // 设置盘点人信息
        if (check.getUId() != null) {
            vo.setUId(check.getUId());
            // 设置盘点人姓名
            String username = userService.getById(check.getUId()).getUsername();
            vo.setChecker(username);
        }

        return vo;
    }

    /**
     * 获取盘点结果描述
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(InventoryCheckAddDTO addDTO) {
        // 生成盘点编号: KCPD + 年月日 + 4位随机数
        String dateStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String randomNum = String.format("%04d", (int)(Math.random() * 10000));
        String checkNo = "KCPD" + dateStr + randomNum;

        // 创建盘点记录
        InventoryCheck check = new InventoryCheck();
        check.setCheckNo(checkNo);
        check.setCheckTime(new Date());
        check.setProductCount(addDTO.getProductCount());
        check.setStockQuantity(addDTO.getStockQuantity());
        check.setCheckTotal(addDTO.getCheckTotal());
        check.setProfitLoss(addDTO.getProfitLoss());
        check.setCheckResult(addDTO.getCheckResult());
        check.setUId(addDTO.getUId());
        check.setRemark(addDTO.getRemark());

        // 保存盘点记录
        return this.save(check);
    }

    @ApiModelProperty("盘点编号(无需填写，系统自动生成)")
    private String checkNo;

    private String getCheckResultDesc(Integer checkResult) {
        if (checkResult == null) {
            return "未知";
        }
        switch (checkResult) {
            case 0: return "盘盈";
            case 1: return "盘亏";
            case 2: return "正常";
            default: return "未知";
        }
    }
}
